﻿using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

namespace CQRS.Reports
{
    public class QueryCriteria
    {
        private readonly Dictionary<string, object> _searchCriteriaDictionary = new Dictionary<string, object>();

        public IEnumerable<string> UsedFields
        {
            get { return _searchCriteriaDictionary.Select(x => x.Key); }
        }

        public IEnumerable<string> Parameters
        {
            get { return _searchCriteriaDictionary.Select(x => x.Key.ToLower()); }
        }

        public bool IsNotEmpty
        {
            get { return _searchCriteriaDictionary.Count > 0; }
        }

        public QueryCriteria AddCriteria(string key, object value)
        {
            _searchCriteriaDictionary.Add(key, value);
            return this;
        }

        public object GetValue(string fieldName)
        {
            object fieldValue;
            _searchCriteriaDictionary.TryGetValue(fieldName, out fieldValue);
            return fieldValue;
        }

        internal void AddParameters(SqlCommand sqlCommand, string parameterPrefix = "")
        {
            foreach (var searchCriteriaPair in _searchCriteriaDictionary)
            {
                sqlCommand.Parameters.Add(
                    new SqlParameter(string.Format("@{0}{1}", parameterPrefix, searchCriteriaPair.Key.ToLower()),
                                     searchCriteriaPair.Value));
            }
        }

        public string GenerateQueryString(string parameterPrefix = "")
        {
            return string.Join(" AND ", _searchCriteriaDictionary
                                            .Select(
                                                x =>
                                                string.Format("{0} = @{2}{1}", x.Key, x.Key.ToLower(), parameterPrefix))
                                            .ToArray());
        }
    }
}